package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.message.FollowBehaviorConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.Utils.threadlocal.AppThreadLocalUtils;
import com.heima.model.article.pojo.ApAuthor;
import com.heima.model.behavior.dto.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.UserRelationDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.pojo.ApUserFan;
import com.heima.model.user.pojo.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by ZYJ on 2021/6/4 17:28
 */
@Service
@Transactional
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    ArticleFeign articleFeign;

    /**
     * 关注或取消关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        if (dto == null || (dto.getOperation() < 0 || dto.getOperation() > 1)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        }
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "作者信息不能为空");
        }
        ApAuthor apAuthor = articleFeign.findById(dto.getAuthorId());
        if (apAuthor == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "关注的用户不存在");
        }
        //判断是否登录
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //如果操作行为是0 关注该作者
        if (dto.getOperation() == 0) {
            return followByUserId(apUser.getId(), apAuthor.getUserId(), dto.getArticleId());
        } else {
            //如果操作行为是 1 取关该作者
            return followCancelByUserId(apUser.getId(), apAuthor.getUserId());
        }


    }

    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    ApUserFollowMapper apUserFollowMapper;
    @Autowired
    ApUserFanMapper fanMapper;
    @Autowired
    KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 取消关注作者
     *
     * @param id
     * @param userId
     * @return
     */
    private ResponseResult followCancelByUserId(Integer id, Integer userId) {
        // 删除当前用户关注信息
        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, userId)
                .eq(ApUserFollow::getUserId, id));
        // 删除被关注的粉丝信息
        fanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId, id)
                .eq(ApUserFan::getUserId, userId));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 关注作者
     *
     * @param id        当前用户
     * @param userId    作者的id
     * @param articleId
     * @return
     */
    private ResponseResult followByUserId(Integer id, Integer userId, Long articleId) {
        ApUser followUser = apUserMapper.selectById(userId);
        if (followUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "关注用户不存在");
        }

        //2 保存当前用户关注信息
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, id)
                .eq(ApUserFollow::getFollowId, userId)
        );

        if (apUserFollow != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST);
        }
        ApUserFollow userFollow = new ApUserFollow();
        userFollow.setUserId(id);
        userFollow.setFollowId(userId);
        userFollow.setFollowName(followUser.getName());
        userFollow.setLevel((short) 1);
        userFollow.setIsNotice(true);
        userFollow.setCreatedTime(new Date());
        apUserFollowMapper.insert(userFollow);
        //3 保存 被关注的作者对应的apUser 对应的粉丝（当前用户）
        //查询粉丝信息(站在当前文章作者角度考虑)
        ApUserFan apUserFan = fanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId, id)
                .eq(ApUserFan::getUserId, userId)
        );
        if (apUserFan != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST);
        }
        ApUserFan userFan = new ApUserFan();
        userFan.setUserId(userId);
        userFan.setFansId((long) id);
        //查询粉丝用户名
        ApUser apUser = apUserMapper.selectById(id);
        userFan.setFansName(apUser.getName());
        userFan.setLevel((short) 0);
        userFan.setCreatedTime(new Date());
        userFan.setIsDisplay(true);
        userFan.setIsShieldLetter(false);
        userFan.setIsShieldComment(false);
        fanMapper.insert(userFan);
        //发送kafka信息到行为微服务保存此用户的关注行为
        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setArticleId(articleId);
        followBehaviorDto.setFollowId(followUser.getId());
        followBehaviorDto.setUserId(apUser.getId());
        //异步发送消息，保存关注行为
        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(followBehaviorDto));
        log.info("发送kafka消息");

        // 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);


    }
}
